package com.web.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -3301605591108950415L;

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    private static final String CLAIM_KEY_ISS = "iss";
    private static final String CLAIM_KEY_SCOPE = "scope";
    private static final String CLAIM_KEY_NONCESTR = "nonceStr";
    @Value("${jwt.secret:wind2015}")
    private String secret;

    @Value("${jwt.expiration:7200}")
    private Long expiration;

    public String getUsernameFromToken(String token) {
        String username;
        try {
            final Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }
    public String getIss(String token) {
        String iss;
        try {
            final Claims claims = getClaimsFromToken(token);
            iss = claims.getIssuer();
        } catch (Exception e) {
            iss=null;
        }
        return iss;
    }
    public String getNonceStr(String token) {
        String iss;
        try {
            final Claims claims = getClaimsFromToken(token);
            iss = (String)claims.get(CLAIM_KEY_NONCESTR);
        } catch (Exception e) {
            iss=null;
        }
        return iss;
    }
    public Date getCreatedDateFromToken(String token) {
        Date created;
        try {
            final Claims claims = getClaimsFromToken(token);
            created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
        } catch (Exception e) {
            created = null;
        }
        return created;
    }

    public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        if(expiration==null) return false;
        return expiration.before(new Date());
    }

    public String generateToken(String username,String iss,String[] scopes) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_ISS,iss);
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_SCOPE,scopes);
        claims.put(CLAIM_KEY_NONCESTR,getRandomStringByLength(16));
        return generateToken(claims);
    }

    public String generateRefreshToken(String username,String iss,String[] scopes,Long time) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_ISS,iss);
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_SCOPE,scopes);
        claims.put(CLAIM_KEY_NONCESTR,getRandomStringByLength(16));
        return   Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + time* 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    public  String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean canTokenBeRefreshed(String token) {
        final Date created = getCreatedDateFromToken(token);
        return  !isTokenExpired(token);
    }

    public String refreshToken(String token) {
        String refreshedToken;
        try {
            final Claims claims = getClaimsFromToken(token);
            claims.put(CLAIM_KEY_CREATED, new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    public Boolean validateToken(String token,String validToken) {
        final Date created = getCreatedDateFromToken(token);
        return (
              StringUtils.equals(token,validToken)
                        && !isTokenExpired(token)
                        );
    }
    public Boolean validateToken(String token) {
        final Date created = getCreatedDateFromToken(token);
        return (
               !isTokenExpired(token)
        );
    }
}

